<template>
	<view class="text-df">
		<view class="detail">
			<!-- 背景图 -->
			<view class="background">
				<image :src="imgURL+ details.indexImg" mode="aspectFill" style="width:100%;"></image>
			</view>

			<view class="" style="background-color: #fff;margin-bottom: 60rpx;">
				<!-- 积分，库存 -->
				<view class="margin-com flex-row-bt" style="font-size: 40rpx;">
					<text class="theme-color">{{details.integratedWorth}}积分</text>
					<text class="text-sm">库存剩余: {{details.inventory}}</text>
				</view>
				<!-- 名称，兑换时间，兑换地点，捐赠人 -->
				<view class="margin-com text-lg">{{details.productName}}</view>

				<view class="margin-com flex-row text-sm" style="" v-if="times.time>0">
					<text>兑换时间：</text>
					<uni-countdown :day="times.day" :hour="times.hour" :minute="times.minu" :second="times.sec"
						color="#EE3F4D" :font-size="12" @timeup="timeup()" />
					<view class="text-sm">后</view>
				</view>

				<view class="margin-com flex-row " style="" @click="navigator(details.exchangeLocation)">
					<text style="width: 650rpx;" class="">兑换地点：{{details.exchangeLocation}}</text>
					<view
						style="background-color: #5090f1; border-radius: 50%; text-align: center; width: 40rpx; height: 40rpx;">
						<view class="iconfont icon-daohang text-white" style="font-size: 30rpx; line-height: 42rpx;">
						</view>
					</view>
					<!-- <image src="../../static/image/detail/position.png" mode="aspectFill"
						style="width:40rpx;height:40rpx;margin-left: auto;"></image> -->
				</view>
				<view class="margin-com flex-row " style="">
					<text>联系电话 ：</text>
					<text>{{details.phone}}</text>
				</view>
				<view class="margin-com flex-row " style="">
					<text v-if="details.sourceCategory==1">捐赠来源 (个人) ：</text>
					<text v-if="details.sourceCategory==2">捐赠来源 (公司) ：</text>
					<text v-if="details.sourceCategory==3">捐赠来源 (组织) ：</text>
					<text v-if="details.sourceCategory==4">捐赠来源 (政府) ：</text>
					<text v-for="i in details.donationSource">{{i}}</text>
				</view>
				<view class="margin-com flex-row " style="" v-if="details.sellByDate!=null">
					<text>保质期 ：</text>
					<text>{{details.sellByDate}}</text>
				</view>
			</view>

			<view v-if="details.kind==1">
				<!-- 产品介绍---物品 -->
				<!-- <view class="introduce margin-tb-com" style="width: 100%;height: fit-content;">
					<view class="margin-com text-lg text-bold" style="">产品介绍</view>
					<view class="expound margin-com border-radius-shadow" style="width: 92%">
						<view class="box box-f flex-row-st" v-if="details.sizeList.length>0">
							<view class="box-left text-mid padding-left-com flex-row-st "
								style="border-radius:20rpx 0 0 0 ;">品牌</view>
							<view class="box-right padding-left-com flex-row-st">{{details.brand}}</view>
						</view>
						<view class="box box-m flex-row-st" v-if="details.functionality!=null">
							<view class="box-left text-mid padding-left-com flex-row-st ">功能性</view>
							<view class="box-right padding-left-com flex-row-st">{{details.functionality}}</view>
						</view>
						<view class="box box-m flex-row-st" v-if="details.sizeList.length>0">
							<view class="box-left text-mid padding-left-com flex-row-st text-bg">尺码</view>
							<view class="box-right padding-left-com flex-row-st">
								<view class="" style="display: flex; flex-wrap: wrap;" v-for="item in details.sizeList">
									<text class="margin-right-xs">{{item}}</text>
								</view>
							</view>
						</view>
						<view class="box box-m flex-row-st" v-if="details.style!=null">
							<view class="box-left text-mid padding-left-com flex-row-st ">风格</view>
							<view class="box-right padding-left-com flex-row-st">{{details.style}}</view>
						</view>
						<view class="box box-m flex-row-st" style="width:100%;" v-if="details.colorList.length>0">
							<view class="box-left text-mid padding-left-com flex-row-st "
								style="border-radius: 0 0 0 20rpx;">颜色分类</view>
							<view class="box-right padding-left-com flex-row-st">
								<view class="" style="display: flex; flex-wrap: wrap;"
									v-for="item in details.colorList">
									<text class="margin-right-xs">{{item}}</text>
								</view>
							</view>
						</view>
					</view>
				</view> -->

				<!-- 详情图片 -->
				<view class="detail " style="">
					<view class="margin-com text-lg text-bold" style="">商品详情</view>
					<image v-for="item in details.imgUrl" :src="imgURL+ item" mode="widthFix" style="width:100%">
					</image>
				</view>


			</view>

			<view v-else>
				<!-- 介绍---服务-->
				<view v-if="details.serviceIntroduce!==null" class="introduce margin-tb-com padding-com"
					style="width: 100%;height: fit-content;">
					<view class="margin-com text-lg text-bold" style="">服务介绍</view>
					<view class="margin-top-sm" style="text-indent: 28rpx">{{details.serviceIntroduce}}</view>
				</view>

				<!-- 服务图片 -->
				<view class="detail " style="">
					<view class="margin-com text-lg text-bold" style="">服务详情</view>
					<image v-for="item in details.imgUrl" :src="imgURL+ item" mode="widthFix" style="width:100%">
					</image>
				</view>
			</view>
			<!-- 底部导航栏 -->
			<view class="" style="width:100%;height:120px;"></view>

			<view class="tabbar flex-row-st bg-white padding-left-sm" style="position: fixed; bottom: 0;
			width:100%;height:110rpx;">
				<!-- 立即兑换 -->
				<button class="theme-bg-color text-white" type="warn" size="mini"
					style="width:75%;height:70rpx; line-height: 70rpx;" @click="onShowSpec">立即兑换</button>

				<!-- 分享 -->
				<button class=" iconfont icon-fenxiang theme-color" open-type="share"
					style="font-size: 60rpx; text-align: center;width: 25%;height: 110rpx;line-height: 110rpx;">
				</button>

			</view>
		</view>
		<!-- 弹窗 -->
		<!-- <uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0">
			<view class="padding-bottom-sm" style="background-color: #fff;width:100%;border-radius: 30rpx 30rpx 0 0;">
				
				<view class="flex-row-st" style="">
					<image class="margin-com " :src="imgURL+ details.indexImg" mode="aspectFill"
						style="width:50px;height:50px"></image>
					<text class="theme-color">{{inventory[current].integratedWorth}}积分</text>
				</view>

				<view class="margin-left-com">分类</view>
				<scroll-view scroll-y="true" class="scroll-Y" style="height: 400rpx;">
					<view class=" padding-tb-sm" style="font-size: 25rpx;width:100%;height:100rpx;">
						<view v-if="details.kind==1" style="display: flex; flex-wrap: wrap;">
							<view
								class="bg-color border-radius-shadow flex-row-ct margin-left-com padding-lr-lg margin-top-xs"
								style="height:60rpx;"
								:style="{color:(index == current ? '#ee3f4d' : ''),border:(index == current ? '1px solid #ee3f4d' : ''),background:(index == current ? '#fff' : '')}"
								v-for="(item,index) in inventory" :key="index">
								<view v-if="item.inventory>0" @click="change_select(index)">
									<text v-if="item.color!=null">{{item.color}}&nbsp;&nbsp;</text>
									<text v-if="item.size!=null">{{item.size}}&nbsp;&nbsp;</text>
									<text v-if="item.specifications!=null">{{item.specifications}}</text>
								</view>
							</view>
						</view>
						<view v-else style="display: flex; flex-wrap: wrap;">
							<view
								class="bg-color border-radius-shadow flex-row-ct margin-left-com padding-lr-lg margin-top-xs"
								style="height:60rpx"
								:style="{color:(index == current ? '#ee3f4d' : ''),border:(index == current ? '1px solid #ee3f4d' : ''),background:(index == current ? '#fff' : '')}"
								v-for="(item,index) in inventory" :key="index">
								<view v-if="item.inventory>0" @click="change_select(index)">
									<text v-if="item.timeInterval!=null">{{item.timeInterval}}&nbsp;&nbsp;</text>
									<text v-if="item.timeSlot!=null">{{item.timeSlot}}</text>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>

				<view class="margin-top-sm flex-row-bt padding-lr-com">
					<view class="">数量</view>
					<uni-number-box :min="1" v-model="number" />
				</view>
				<button class="theme-bg-color margin-left-com margin-top-lg" type="warn" size="mini"
					:disabled="isExchange" style="color:#fff;width:90%;height:70rpx;align-items: center;"
					@click="toExchange">立即兑换</button>
			</view>
		</uni-popup> -->

		<!-- 确认兑换 -->
		<uni-popup ref="confirm_popup" type="dialog">
			<uni-popup-dialog title="订单确认" :duration="2000" :before-close="true" @close="confirm_close" mode="input"
				@confirm="confirm_confirm">
				<view style="width: 100%;">
					<view class="flex-row-bt">
						<image class=" " :src="imgURL+ details.indexImg" mode="aspectFill"
							style="width:100rpx;height:100rpx"></image>
						<view class="margin-right-xs">
							<view class="flex-row-bt " style="width: 100%;">
								<view class="">{{param.productName}}</view>
								<view class=" theme-color text-bold margin-left-xs">{{param.monovalent}}积分</view>
							</view>
							<view class="flex-row-bt text-sm text-low margin-top-lg">
								<view class="">{{param.color}} , {{param.size}}</view>
								<view class="">×{{param.productNumber}}</view>
							</view>
						</view>
					</view>
					<view class="margin-top-sm">
						当前<text class="theme-color margin-lr-xs text-bold">{{store.state.point}}</text>积分，是否使用<text
							class="theme-color margin-lr-xs text-bold">{{parseInt(param.productNumber)*param.monovalent}}</text>积分兑换该商品
					</view>
				</view>
			</uni-popup-dialog>
		</uni-popup>
		<uni-popup ref="popupRef" type="bottom">
			<view class="spec-popup">
				<view @click="onCloseSpec" class="spec-popup_close l-f l-row-c" hover-class="hover-class">
					<uni-icons type="closeempty" size="28" color="#5e6d82"></uni-icons>
				</view>
				<view class="popup-container">
					<view class="spec-popup_info l-f l-col-end">
						<view class="spec-popup_info_left">
							<image 
							@click="onPreviewImage(currentProductObj.image)"
							class="spec-popup_info_left_cover" 
							:src="currentProductObj.image" 
							mode="aspectFill"></image>
						</view>
						<view class="spec-popup_info_right">
							<view>
								<text class="spec-popup_info_right_unit">￥</text>
								<text class="spec-popup_info_right_price">{{currentProductObj.price}}</text>
							</view>
							<view class="spec-popup_info_right_number">库存{{totalStock}}件</view>
							<view class="spec-popup_info_right_select l-line1">已选： {{selectName}}</view>
						</view>
					</view>
					<!-- 选择 -->
					<scroll-view scroll-y="true" class="popup-content" style="height: 500rpx;">
						<view class="">
							<select-box
							v-for="(item,index) in productList" 
							:key="index"
							:title="item.name" 
							:list="item.list"
							:current="productColumns[index]"
							@change="selectChange(index,$event)"></select-box>
						</view>
					</scroll-view>
					<!-- 数量 -->
					<view>
						<view class="margin-top-sm flex-row-bt padding-lr-com">
							<view class="">数量</view>
							<uni-number-box :min="1" v-model="number" @change="numberChange" />
						</view>
						<button class="theme-bg-color margin-left-com margin-top-lg" type="warn" size="mini"
							:disabled="isExchange" style="color:#fff;width:90%;height:70rpx;line-height: 70rpx;align-items: center;"
							>立即兑换</button>
					</view>
				</view>
			</view>
		</uni-popup>



		<!-- 加载 -->
		<loading></loading>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive , computed , nextTick } from 'vue';
	import { getInventoryInfo, getProductInfo, updateStatus } from '../../api/exchange/exchange';
	import { onLoad } from "@dcloudio/uni-app"
	import { imgURL } from '../../api/request';
	import { getRestTime } from '../../utils/time';
	import { redeemPoints } from '../../api/point/point';
	import store from '../../store/login';

	//产品详情
	let details = ref({})

	const times = ref({
		time: 0,//剩余秒数
		day: 0,
		hour: 0,
		minu: 0,
		sec: 0
	})

	//是否可以兑换
	const isExchange = ref(true)

	//库存信息
	const inventory = ref([{
		"color": "白色",
		"id": "1773235925217206274",
		"integratedWorth": "500",
		"inventory": 50,
		"productId": "6",
		"size": "",
		"specifications": "",
		"timeInterval": "",
		"timeSlot": "",
	}])

	//选择商品数量
	const number = ref(1)

	//选择商品信息
	let param = reactive({
		productId: '',
		productName: '',
		monovalent: 0,
		productNumber: 0,
		color: '',
		size: '',
		timeSlot: '',
		specifications: '',
		timeInterval: ''
	})

	//经纬度
	const tude = reactive({
		longitude: '',
		latitude: ''
	})

	onLoad((option) => {
		const id = option.id
		//请求详情
		get_detail(id)
		get_detail2(id)

	})

	//请求详情
	const get_detail = (id : string) => {
		getProductInfo({
			productId: id
		}).then((res : any) => {
			console.log('xqing', JSON.stringify(res.data))
			details.value = res.data
			console.log(details.value, "+++++++++++")
			if (res.data.releaseTime != null || res.data.releaseTime != '') {
				times.value = getRestTime(res.data.releaseTime)
				if (times.value.time <= 0) {
					timeup()
					isExchange.value = false
				}
			}
			//获取经纬度
			getTude()
		})
	}

	//商品库存请求
	const get_inventory = () => {
		getInventoryInfo({
			productId: details.value.id
		}).then((res : any) => {
			inventory.value = res.data
			console.log('库存', JSON.stringify(res.data))
		})
	}

	//修改待上架商品状态
	const timeup = () => {
		times.value.time = 0
		updateStatus({
			productId: details.value.id
		}).then((res : any) => {
		})
	}

	//立即兑换
	const toExchange = () => {
		//判断是否登录
		if (store.state.token == '') {
			store.loginTip()
		} else if (store.state.point < number.value * Number(inventory.value[current.value].integratedWorth)) {
			uni.showToast({
				title: '积分不足',
				icon: 'none',
				duration: 2000
			});
		} else {
			param.productId = inventory.value[current.value].productId,
			param.productName = details.value.productName,
			param.monovalent = inventory.value[current.value].integratedWorth,
			param.productNumber = number.value,
			param.color = inventory.value[current.value].color,
			param.size = inventory.value[current.value].size,
			param.timeSlot = inventory.value[current.value].timeSlot,
			param.specifications = inventory.value[current.value].specifications,
			param.timeInterval = inventory.value[current.value].timeInterval

			//打开确认弹窗
			confirm_open()
		}
	}

	//兑换积分
	const exchang_point = () => {
		console.log(number.value)
		console.log('兑换参数' + JSON.stringify(param))
		redeemPoints([param]).then((res : any) => {
			if (res.code == 200) {
				uni.showToast({
					title: '兑换成功',
					icon: 'none',
					duration: 2000
				});
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/mines/my_exchange/my_exchange?index=' + '1'
					})
				}, 500)
			}
		})
	}

	//弹窗
	const popup = ref(null)

	const openPop = () => {
		// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
		popup.value.open()
		//请求库存
		get_inventory()
	}

	//商品选择切换
	const current = ref(0)
	const change_select = (index : any) => {
		console.log(index)
		current.value = index
	}

	//分享
	const share = () => {
		uni.showToast({
			title: '功能正在开发中...',
			icon: 'none',
			duration: 2000
		});
	}

	//确认弹窗
	const confirm_popup = ref(null)

	//打开弹窗
	const confirm_open = () => {
		confirm_popup.value.open()
	}

	const confirm_close = () => {
		confirm_popup.value.close()
	}

	const confirm_confirm = (value) => {
		console.log(value)
		confirm_popup.value.close()
		//兑换积分
		exchang_point()
	}

	//导航
	const navigator = (name : any) => {
		wx.openLocation({
			latitude: Number(tude.latitude),
			longitude: Number(tude.longitude),
			name: details.value.exchangeLocation,
			scale: 12
		})
	}

	//获取经纬度
	const getTude = () => {
		console.log('地点' + details.value.exchangeLocation)
		uni.request({
			url: 'https://restapi.amap.com/v3/geocode/geo?parameters',
			method: 'GET',
			data: {
				key: '84b002e324e6d4e5e6b9541c6cbf8b71',
				address: details.value.exchangeLocation
			},
			success: (res) => {
				console.log(JSON.stringify(res.data))
				tude.longitude = res.data.geocodes[0].location.split(',')[0]  //经度
				tude.latitude = res.data.geocodes[0].location.split(',')[1]  //维度
				console.log(tude.longitude, tude.latitude)

			}
		})
	}



	const popupRef = ref(null)

	// 规格显示
	const onShowSpec = () => {
		popupRef.value.open()
	}
	// 规格隐藏
	const onCloseSpec = () => {
		popupRef.value.close()
	}

	// 商品详情
	let productDetail = reactive({
		bannerList: [], // 轮播
		stock: 0, // 总库存
		sales: 0, // 总销量
		storeName: '', // 商品名称
		unitName: '', // 单位
		content: '', // 商品详情
		storeInfo: '', // 商品简介
		price: '', // 商品价格
	})
	const productList = ref([]) // 规格列表
	const productColumns = ref([]) // 规格选择下标
	let productValueObj = reactive({}) // 所有规格属性对象
	// 当前选中产品
	let currentProductObj = reactive({
		image: '', // 主图
		price: '', // 售价
		
	})
	// 数量
	const numberChange = (value) => {
		nextTick(()=>{
			number.value = value > totalStock.value ? totalStock.value : value
		})
	}


	// 计算库存
	const totalStock = computed(() => {
		let total = 0
		let filterProductValueObj = {...productValueObj}
		// 过滤选择的规格
		for (let i = 0; i < productColumns.value.length; i++) {
			let currentColumn = productColumns.value[i]
			let currentProduct = productList.value[i]
			if(currentColumn > -1) {
				let filterObj = {}
				// 判断key是否相等
				for (let key in filterProductValueObj) {
					if(currentProduct.list[currentColumn].label === filterProductValueObj[key].attrValue[productList.value[i].name]) {
						filterObj[key] = filterProductValueObj[key]
					}
				}
				filterProductValueObj = {...filterObj}
			}
		}
		let productArr = []
		// 遍历符合条件商品
		for (let key in filterProductValueObj) {
			total += filterProductValueObj[key].stock
			productArr.push(filterProductValueObj[key])
		}
		// 当前选择商品-默认第一个
		currentProductObj.image = productArr[0].image
		currentProductObj.price = productArr[0].price
		return total
	})
	// 计算选择显示
	const selectName = computed(() => {
		let nameArr = []
		for (let i = 0; i < productList.value.length; i++) {
			if(productColumns.value[i] > -1) {
				nameArr.push(productList.value[i].list[productColumns.value[i]].label)
			}
		}
		if(nameArr.length > 0) {
			return nameArr.join(' | ')
		}
		return ''
	})

	// 规格选择
	const selectChange = (index,value) => {
		productColumns.value[index] = productColumns.value[index] === value ? -1 : value
		
		
		number.value = number.value > totalStock.value ? totalStock.value : number.value

		// 商品规格匹配
		for (let i = 0; i < productList.value.length; i++) {
			let keyName = productList.value[i].name
			let currentKeyName = productList.value[index].name
			// 判断除当前选择的以外规格
			if(index !== i) {
				// 获取属性相同的
				for (let key in productValueObj) {
					if(productList.value[index].list[value].label === productValueObj[key].attrValue[currentKeyName]) {
						// 判断库存
						for (let j = 0; j < productList.value[i].list.length; j++) {
							if(productList.value[i].list[j].label === productValueObj[key].attrValue[keyName]){
								productList.value[i].list[j].disabled = productValueObj[key].stock <= 0 ? true : false
							}
						}
					}
				}
			}
		}
	}
	// 小图预览
	const onPreviewImage = (url: string) => {
		uni.previewImage({
			urls: [url],
			current: url
		})
	}

	//请求商品详情 '1780640329198743552'
	const get_detail2 = (id) => {
		uni.request({
			url: 'http://192.168.110.30:9091/product/detail/1?type=normal',
			success: (res) => {
				let data = res.data
				if(data.code === 200) {
					const {productInfo,productAttr,productValue} = data.data
					// 轮播图处理
					let bannerArr = []
					try{
						bannerArr = JSON.parse(productInfo.sliderImage)
					}catch(e){
						//TODO handle the exception
					}
					productDetail.bannerList = bannerArr // 轮播
					productDetail.stock = productInfo.stock // 总库存
					productDetail.sales = productInfo.sales // 总销量
					productDetail.storeName = productInfo.storeName // 商品名称
					productDetail.unitName = productInfo.unitName // 单位
					productDetail.content = productInfo.content // 商品详情
					productDetail.storeInfo = productInfo.storeInfo // 商品简介
					productDetail.price = productInfo.price // 商品价格
					
					console.log(productDetail)
					
					// 商品规格处理
					let productArr = []
					let productColumnsArr = []
					for (let i = 0; i < productAttr.length; i++) {
						let list = []
						try{
							let attrArr = productAttr[i].attrValues.split(',')
							// 追加属性上去
							for (let j = 0; j < attrArr.length; j++) {
								list.push({
									label: attrArr[j],
									disabled: false
								})
							}
						}catch(e){
							console.log('产品规格解析失败',productAttr[i].attrValues)
						}
						productArr.push({
							name: productAttr[i].attrName,
							list
						})
						productColumnsArr.push(-1)
					}
					productList.value = productArr
					productColumns.value = productColumnsArr
					// 商品规格详情处理
					for (let key in productValue ) {
						try{
							productValue[key].attrValue = JSON.parse(productValue[key].attrValue)
						}catch(e){
							productValue[key].attrValue = {}
						}
					}
					productValueObj = productValue
				}
				console.log(data.data)
			}
		})
	}



</script>

<style lang="scss" scoped>
	.detail {
		.introduce {
			.expound {
				.box {
					width: 100%;
					height: 100rpx;
					font-size: 30rpx;
					font-weight: bold;

					.box-left {
						width: 40%;
						height: 100%;
						border-right: 1px solid #d9d9d9;
						background-color: $bg-color;
					}

					.box-right {
						width: 60%;
						height: 100%;
						background-color: #fff;
					}
				}

				.box-m {
					border-top: 1px solid #D9D9D9;
				}
			}
		}
	}

	.tabbar {
		box-shadow: $uni-shadow-lg;
	}

	Button::after {
		border: none;
	}

	page {
		background-color: #f7f7f7;
	}
	.banner {
		position: relative;
		&_swiper {
			height: 650rpx;
			&_item {
				&_image {
					width: 100%;
					height: 100%;
				}
			}
		}
		&_share {
			background-color: rgba(0,0,0,.5);
			position: absolute;
			right: 30rpx;
			bottom: 30rpx;
			color: #ffffff;
			font-size: 28rpx;
			height: 60rpx;
		}
	}
	.popup-content{
		flex: 1 0 auto; /* 中间自动填充剩余空间 */
	}

	.popup-container {
		display: flex;
		flex-direction: column;
		height: 100%;
	}
	// 规格弹窗
	.spec-popup {
		background-color: #ffffff;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		padding: 30rpx;
		box-sizing: border-box;
		height: 70vh;
		position: relative;
		&_close {
			position: absolute;
			right: 30rpx;
			top: 30rpx;
			width: 50rpx;
			height: 50rpx;
		}
		&_info {
			&_left {
				&_cover {
					width: 186rpx;
					height: 200rpx;
					background-color: #f5f5f5;
					border-radius: 12rpx;
				}
			}
			&_right {
				margin-left: 20rpx;
				&_unit {
					font-size: 24rpx;
					color: #000000;
					font-weight: 700;
				}
				&_price {
					font-size: 32rpx;
					color: #000000;
					font-weight: 700;
				}
				&_number {
					margin-top: 10rpx;
					font-size: 28rpx;
					color: #999999;
				}
				&_select {
					margin-top: 10rpx;
					font-size: 28rpx;
					color: #000000;
				}
			}
		}
	}
</style>